import { Component, OnInit, ViewChild, Input, SimpleChanges, SimpleChange } from '@angular/core';
import { FileUpload } from 'primeng/fileupload';
import { Message, ConfirmationService } from 'primeng/api';
import { PropertyService } from '../../service/property.service';
import { ConstantVariable, PropertyMenuKeys } from '../../../shared/config/app-settings';
import { UserService } from '../../../shared/services/user.service';
import { AttachmentUtilsService } from '../../../shared/services/attachment-utils.service';

@Component({
  selector: 'app-property-detail-resources',
  templateUrl: './property-detail-resources.component.html',
  styleUrls: ['./property-detail-resources.component.css']
})
export class PropertyDetailResourcesComponent implements OnInit {
  user:any = {};
  msgs: Message[] = [];
  isEditPanelVisible: boolean = false;

  @Input() id: number = 1;
  @Input() menuKey: string = '';

  attachmentKey: string;
  property: any = {};

  richText: string;
  attachments: any[];

  constructor(private PropertyService: PropertyService,
    private confirmationService: ConfirmationService,
    private userService: UserService,
    private attachmentUtilsService:AttachmentUtilsService
    ) { }

  ngOnInit() {
    this.enrichAttachmentKey();
    this.loadProperty();
    this.getCurrentUser();

  }

  ngOnChanges(changes: SimpleChanges) {
    console.log("ngOnChanges");
    this.isEditPanelVisible = false;
    this.enrichAttachmentKey();
    this.loadProperty();
  }

  //ui-event
  onEdit() {
    this.isEditPanelVisible = true;
  }

  onClose() {
    this.isEditPanelVisible = false;
  }
  onSave() {
    let resultProperty = { id: this.property.id, }
    this.enrichTextField(resultProperty);
    this.updateProperty(resultProperty);

  }

  onFileUpload(fileUploader) {
    this.confirmationService.confirm({
      message: '<p class="text-danger">Save text before operating attachments, otherwise text will lost.</p>Are you sure that you want to upload file now?',
      accept: () => {
        this.uploadFile(fileUploader);
      }
    });

  }

  onDeleteFile(attachment) {
    this.confirmationService.confirm({
      message: '<p class="text-danger">Save text before operate attachments, otherwise text will lost.</p>Are you sure that you want to delete this file?',
      accept: () => {
        this.deleteFile(attachment);
      }
    });

  }

  showInfo(message) {
    this.msgs.push({ severity: 'info', summary: 'Message', detail: message });
  }

  showError(message) {
    this.msgs.push({ severity: 'error', summary: 'Message', detail: message });
  }

  //server exchange
  loadProperty() {
    this.PropertyService.getPropertyById(this.id).subscribe(
      (res) => {
        this.PropertyService.escapeAll(res, false);
        this.property = res;
        this.richText = this.getPropertyText();
        this.attachments = this.getPropertyAttachment();
        console.log(this.richText);
      },
      (err) => {
        console.log(err);

      }
    )
  }

  updateProperty(resultProperty) {
    this.PropertyService.updateProperty(resultProperty).subscribe(
      (res) => {
        console.log(res);
        this.showInfo("update success");
        this.isEditPanelVisible = false;
        this.loadProperty();
      },
      (err) => {
        console.log(err);
        this.showError("update fail");
      }
    )
  }

  uploadFile(fileUploader) {
    if (this.property.id <= 0) {
      this.showError("property is id!");
      this.onSave();
    }
    //  tab1
    let attachment = {
      belongToID: this.id,
      belongToCategory: this.attachmentKey,
      files: fileUploader.files
    };
    this.PropertyService.uploadFile(attachment).subscribe(
      (res) => {
        this.showInfo(" Attahement update success");
        fileUploader.clear();
        this.loadProperty();
      },
      (err) => {
        this.showError(" Attachment update fail");
      }
    );
  }

  deleteFile(attachment) {
    this.attachmentUtilsService.deleteFile(attachment.id).subscribe(
      (res) => {
        this.showInfo(attachment.originalFilename + " delete success");
        this.loadProperty();
      },
      (err) => {
        this.showError(attachment.originalFilename + " delete fail");
      }
    );
  }

  getCurrentUser(){
    this.userService.getCurrentUser().subscribe((user)=>{
      this.user = user;
    });
  }

  //ngModel bind text field
  getPropertyText() {
    if (this.menuKey === PropertyMenuKeys.CONTRACT_OF_SALE)
      return this.property.textContractOfSale;
    else if (this.menuKey === PropertyMenuKeys.DEPOSIT_FORM)
      return this.property.textDepositForm;
    else if (this.menuKey === PropertyMenuKeys.SOLICITOR_CONTRACT)
      return this.property.textSolicitor;
    else if (this.menuKey === PropertyMenuKeys.BILLS_CHARGES)
      return this.property.textBillsCharges;
    else if (this.menuKey === PropertyMenuKeys.MANAGEMENT_AGREEMENT)
      return this.property.textManagementAgreement;
    else if (this.menuKey === PropertyMenuKeys.OTHERS)
      return this.property.textOthers;

  }
  isShowUploader() {
    if (this.menuKey === PropertyMenuKeys.SOLICITOR_CONTRACT)
      return false;
    else return true;
  }




  //bind attachment
  getPropertyAttachment() {

    if (this.attachmentKey === ConstantVariable.BELONG_TO_PROPERTY_COS_DOCUMENT)
      return this.property.property_cos_document;
    else if (this.attachmentKey === ConstantVariable.BELONG_TO_PROPERTY_DEPOSIT_FORM_DOCUMENT)
      return this.property.property_deposit_form_document;
    else if (this.attachmentKey === ConstantVariable.BELONG_TO_PROPERTY_BILL_CHARGES)
      return this.property.property_bill_charges;
    else if (this.attachmentKey === ConstantVariable.BELONG_TO_PROPERTY_MANAGEMENT_AGREEMENT)
      return this.property.property_management_agreement_document;
    else if (this.attachmentKey === ConstantVariable.BELONG_TO_PROPERTY_OTHERS)
      return this.property.property_others;

  }

  enrichAttachmentKey() {
    if (this.menuKey === PropertyMenuKeys.CONTRACT_OF_SALE)
      this.attachmentKey = ConstantVariable.BELONG_TO_PROPERTY_COS_DOCUMENT;
    else if (this.menuKey === PropertyMenuKeys.DEPOSIT_FORM)
      this.attachmentKey = ConstantVariable.BELONG_TO_PROPERTY_DEPOSIT_FORM_DOCUMENT;
    else if (this.menuKey === PropertyMenuKeys.SOLICITOR_CONTRACT)
      this.attachmentKey = "";
    else if (this.menuKey === PropertyMenuKeys.BILLS_CHARGES)
      this.attachmentKey = ConstantVariable.BELONG_TO_PROPERTY_BILL_CHARGES;
    else if (this.menuKey === PropertyMenuKeys.MANAGEMENT_AGREEMENT)
      this.attachmentKey = ConstantVariable.BELONG_TO_PROPERTY_MANAGEMENT_AGREEMENT;
    else if (this.menuKey === PropertyMenuKeys.OTHERS)
      this.attachmentKey = ConstantVariable.BELONG_TO_PROPERTY_OTHERS;
  }

  enrichTextField(resultProperty) {
    if (this.menuKey === PropertyMenuKeys.CONTRACT_OF_SALE)
      resultProperty['textContractOfSale'] = this.PropertyService.escapeText(this.richText, true);
    else if (this.menuKey === PropertyMenuKeys.DEPOSIT_FORM)
      resultProperty['textDepositForm'] = this.PropertyService.escapeText(this.richText, true);
    else if (this.menuKey === PropertyMenuKeys.SOLICITOR_CONTRACT)
      resultProperty['textSolicitor'] = this.PropertyService.escapeText(this.richText, true);
    else if (this.menuKey === PropertyMenuKeys.BILLS_CHARGES)
      resultProperty['textBillsCharges'] = this.PropertyService.escapeText(this.richText, true);
    else if (this.menuKey === PropertyMenuKeys.MANAGEMENT_AGREEMENT)
      resultProperty['textManagementAgreement'] = this.PropertyService.escapeText(this.richText, true);
    else if (this.menuKey === PropertyMenuKeys.OTHERS)
      resultProperty['textOthers'] = this.PropertyService.escapeText(this.richText, true);
  }



}
